package com.komorebishao.code;

public class Code844 {

    public static void main(String... args) {
        String s = "ab#c";
        String t = "ab#c";
        compareStrs(s, t);
     }


    public boolean backSpaceCompare(String s, String t) {
        return buildResult(s).equals(buildResult(t));
    }

    public String buildResult(String str) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch != '#') {
                result.append(ch);
            } else {
                if (result.length() > 0) {
                    result.deleteCharAt(result.length() - 1);
                }
            }
        }
        return result.toString();
    }

    public static boolean compareStrs(String s, String t) {
        int lengthOfS = s.length() - 1;
        int lengthOfT = t.length() - 1;
        int deleteNumsOfS = 0, deleteNumsOfT = 0;

        while (lengthOfT >= 0 || lengthOfS >= 0) {
            while (lengthOfS >= 0) {
                if (s.charAt(lengthOfS) == '#') {
                    deleteNumsOfS++;
                    lengthOfS--;
                } else if (deleteNumsOfS > 0) {
                    deleteNumsOfS--;
                    lengthOfS--;
                } else {
                    break;
                }
            }
            while (lengthOfT >= 0) {
                if (t.charAt(lengthOfT) == '#') {
                    deleteNumsOfT++;
                    lengthOfT--;
                } else if (deleteNumsOfT > 0) {
                    deleteNumsOfT--;
                    lengthOfT--;
                } else {
                    break;
                }
            }
            if (lengthOfT >= 0 && lengthOfS >= 0) {
                if (s.charAt(lengthOfS) != t.charAt(lengthOfT)) {
                    return false;
                }
            }
            lengthOfS--;
            lengthOfT--;
        }
        return true;
    }
}
